package com.devshephard.jucks.lock.ticketLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketLock {

    public static void main(String[] args) {

        //ticketLock.Ticket2 ticket = new ticketLock.Ticket2();

        Ticket1 ticket = new Ticket1();


        new Thread(()->{
            for (int i = 0; i < 30; i++) {
                ticket.sellTicket();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 30; i++) {
                ticket.sellTicket();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 30; i++) {
                ticket.sellTicket();
            }
        },"C").start();



      /*  new Thread(()->{

            try {
                ticket.testOneLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"D").start();


        new Thread(()->{

                ticket.testTwoLock();

        },"E").start();*/

    }



}

class Ticket1{

    private Lock lock = new ReentrantLock();

    private Integer ticketNumber = 50;

    public  void sellTicket(){

        lock.lock();

        try {
            if(ticketNumber > 0){
                System.out.println(Thread.currentThread().getName() + "当前已售出票：" + ticketNumber -- + "还剩余票：" + ticketNumber);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }


    public  void testOneLock() throws InterruptedException {

        lock.lock();

        try {
            System.out.println(Thread.currentThread().getName() + "获取锁");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Thread.sleep(10000);
            lock.unlock();
        }

    }

    public  void testTwoLock(){

        lock.lock();

        try {

                System.out.println(Thread.currentThread().getName() + "获取锁");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}


class Ticket2{

   private Integer ticketNumber = 50;

   public synchronized void sellTicket(){

       if(ticketNumber > 0){
           System.out.println(Thread.currentThread().getName() + "当前已售出票：" + ticketNumber -- + "还剩余票：" + ticketNumber);
       }

   }
}